interface IlocationScope extends ng.IScope{
    /**
     * 定位按钮
     */
    locaBtn:string;
    /**
     * 车辆id
     */
    carId:string;
    /**
     * 是否为车辆定位
     */
    isVehicle:boolean;
    /**
     * 开通定位Dis
     */
    dredgeDis:boolean;
    /**
     * 定位dis
     */
    locaDis:boolean;
    /**
     * 车牌号
     */
    carCode:string;
    /**
     * 定位日期
     */
    creationTime:string;
    /**
     * 定位情况
     */
    statusCode:string;
    /**
     * 手机号码
     */
    phoneNumber:string;
    /**
     * 发货地址
     */
    shipAddress:string;
    /**
     * 位置信息
     */
    areaInfo:string;
    /**
     * 历史定位日期
     */
    oldcreationTime:string;
    /**
     * 历史位置信息
     */
    oldAreaInfo:string;
    /**===================================== */
    /**
     * "是否开通定位功能"是否开启
     */
    isdisabled1:boolean;
    /**
     * locBtn是否开启
     */
    isdisabled2:boolean;
    /**
     * 点击定位事件，必须是已开通
     */
    getlocation:(carId:string,isVehicle)=>void;
    /**
     * 开通注册功能，必须是已开通
     */
    dredge:(carId:string,isVehicle:boolean)=>void;
    //点击关闭按钮，消除所有地图标点和定位数据
    deletePoint:()=>void;
     /**
     * 收货地址
     */
    deliverAddress:string;
    
}


function tmsCarlocation(locationService:ILocationService, $ngBootbox:BootboxService): ng.IDirective{
    return {
        restrict: 'E',
        templateUrl:'./src/directives/tms-carLocation/tms-carLocation.html',
        transclude: true,
        link  : ($scope: IlocationScope) =>{
            $scope.locaBtn="定位";
            let carId:string=$scope.carId;
            let isVehicle:boolean=$scope.isVehicle=true;

            let isdisabled1:boolean=$scope.isdisabled1=true;
            let isdisabled2:boolean=$scope.isdisabled2=true;
            let creationTime:string=$scope.creationTime="";

            let areaInfo:string=$scope.areaInfo;

            $scope.oldcreationTime="";
            $scope.oldAreaInfo="";

            // //页面进入时,地图初始化,逆地址解析实例
            // $('document').ready(function(){
                
            // })p
            
            function initMap(ishide?:boolean){
                createMap(ishide); //创建地图
                setMapEvent(); //设置地图事件
                addMapControl(); //向地图添加控件
            }
            
            //创建地图函数：
          
            let map;
            let hasMap:boolean;
            /**
             * 如果之前实例化过地图对象，则不能再次实例化一个对象。因为new BMap.Map("dituContent")方法只能调用一次。如果多次调用，地图呈现会出错。
             * 
             */
            // if(window['map']){
            //     map=window['map'];
            //     hasMap=true;
            //     setTimeout(()=>{
            //         map.clearOverlays()
            //         $('#mapDiv')[0].innerHTML='';
            //         $('#mapDiv')[0].appendChild(map.Va)
            //     },500)
            // }else{
                
            // }

            $("#location").show();
            map = new BMap.Map("dituContent"); //在百度地图容器中创建一个地图
            hasMap=false;

           setTimeout(function(){initMap(true);},200);
           
            
            function createMap(ishide?:boolean) {
                let point = new BMap.Point(119.425882, 32.208785); //定义一个中心点坐标
                //如果之前有map对象，则不需要对其初始化
                if(hasMap){
                    return;
                }
                map.centerAndZoom(point, 10); //设定地图的中心点和坐标并将地图显示在地图容器中
                if(ishide){
                    $("#location").hide();
                }
                window['map'] = map; //将map变量存储在全局
            }

            //地图事件设置函数：
            function setMapEvent() {
                map.enableScrollWheelZoom(); //启用地图滚轮放大缩小
            }

            //地图控件添加函数：
            function addMapControl() {
                //向地图中添加缩放控件
                let ctrl_nav = new BMap.NavigationControl({
                    anchor: BMAP_ANCHOR_TOP_LEFT,
                    type: BMAP_NAVIGATION_CONTROL_LARGE
                });
                map.addControl(ctrl_nav);
                //向地图中添加比例尺控件
                let ctrl_sca = new BMap.ScaleControl({
                    anchor: BMAP_ANCHOR_BOTTOM_LEFT
                });
                map.addControl(ctrl_sca);
            }

            //创建InfoWindow
            let markerArr:any[];
            function createInfoWindow(i) {
                let json = markerArr[i];
                let iw = new BMap.InfoWindow("<b class='iw_poi_title' title='" + json.title + "'>" + json.title + "</b><div class='iw_poi_content'>" + json.content + "</div>");
                return iw;
            }

            // 编写创建标注函数
            function addMarker(point, label) {
                let marker = new BMap.Marker(point);
                map.addOverlay(marker);
                marker.setLabel(label);
            }

            //逆地址解析函数,起始点使用
            function s_e(adds) {
                myGeo.getPoint(adds, function (point) {
                    if (point) {
                        let address = new BMap.Point(point.lng, point.lat);
                        addMarker(address, new BMap.Label(adds, {
                            offset: new BMap.Size(20, -10)
                        }));
                    }
                });
            }

            //判断开通注册状态
            function getlocastate(carid, isVehicle) {
                locationService.getLocationState(carid, isVehicle).then(
                    function (res:LocationListItemResponse) {
                        if (res.isRegister == true) {
                            $scope.isdisabled1 = true;
                            $scope.isdisabled2 = false;

                        } else {
                            $scope.isdisabled1 = false;
                            $scope.isdisabled2 = true;
                        }
                    },
                    function (rej) {
                        $scope.isdisabled1 = true;
                        $scope.isdisabled2 = true;
                        console.error(rej);
                    }
                )
            }

            //历史定位
            function history_location(carid, isVehicle) {
                locationService.getHistoryLocation(carid, isVehicle).then(
                    function (resq) {
                        $scope.oldAreaInfo = resq.data.area;
                        $scope.oldcreationTime = resq.data.creationTime;
                    },
                    function (rel) {
                        console.log(rel)
                    }
                );
            }

            //点击定位事件,必须是已开通
            $scope.getlocation = function (carid, isVehicle) {
                $scope.locaBtn = "定位中，请稍等...";
                $scope.isdisabled2 = true;
                $scope.creationTime = "";
                $scope.statusCode = "";
                $scope.areaInfo = "";
                initMap(false);
                //起始点名称数组
                let shipAddress = $scope.shipAddress;
                let deliverAddress = $scope.deliverAddress;
                let adds = [shipAddress, deliverAddress];
                for (let i = 0; i < adds.length; ++i) {
                    s_e(adds[i]);
                }
                locationService.getLocation(carid, isVehicle).then(
                    function (resq) {
                        $scope.areaInfo = resq.data.area;
                        $scope.creationTime = resq.data.creationTime;
                        $scope.statusCode = "定位成功";

                        // 百度API
                        let p0 = resq.data.longitude;
                        let p1 = resq.data.latitude;
                        let pt = new BMap.Point(p0, p1);
                        addMarker(pt, new BMap.Label($scope.areaInfo, { offset: new BMap.Size(20, -10) }));
                        $scope.locaBtn = "定位";
                        $scope.isdisabled1 = true;
                    },

                    function (resl) {
                        $scope.statusCode = "定位失败";
                        $scope.locaBtn = "定位";
                        $scope.isdisabled1 = true;
                        $scope.isdisabled2 = false;
                    }
                );
                history_location(carid, isVehicle);
            }

            //点击开通注册功能，必须是未开通
            $scope.dredge =  (carid, isVehicle) => {
                $scope.isdisabled1 = true;
                locationService.getDredge(carid, isVehicle).then(
                    (res) =>{
                        if (res.data.isRegister == true) {
                             $ngBootbox.alert('驾车司机短信同意开通才能使用定位！,同意后刷新一次页面！')
                        } else {
                            $scope.isdisabled1 = false;
                        }

                    },
                    (rel) =>{
                        
                        $scope.isdisabled1 = false;
                    })
            }

            //点击关闭按钮，消除所有地图标点和定位数据
            $scope.deletePoint =  () => {
                let allOverlay = map.getOverlays();
                console.log(allOverlay)
                for (let i = 0; i < allOverlay.length - 1; i++) {
                    map.removeOverlay(allOverlay[i + 1]);
                }
                $scope.creationTime = "";
                $scope.statusCode = "";
                $scope.areaInfo = "";
            }



            
            let myGeo = new BMap.Geocoder();

            //判断carid是否取得
            if ($scope.carId == null || $scope.carId == "") {
                console.log("还未获取车辆id")
            } else {
                //页面加载时，判断是否开通注册
                getlocastate(carId, isVehicle);
            }
        }

    }
}


tmsCarlocation['$inject'] = ["locationService","$ngBootbox"]
angular.module('tmsCarlocation', []).directive('tmsCarlocation',tmsCarlocation);